package com.kikt.webviewdemo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import butterknife.Bind;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "HELLL";
    @Bind(R.id.wv)
    WebView mWv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        butterknife.ButterKnife.bind(this);

        initWebView();

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = mWv.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setSaveFormData(false);
        settings.setSupportZoom(false);
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        mWv.setWebChromeClient(new MyWebViewClient());
        mWv.addJavascriptInterface(new DemoJS(), "demo");
        mWv.loadData("", "text/html", null);

        mWv.loadUrl("http://192.168.1.105:8080/test.html");
    }

    public class MyWebViewClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }

    final public class DemoJS {
        public DemoJS() {

        }

        @JavascriptInterface
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("DemoJS", "test");
                    mWv.loadUrl("javascript:wave()");
                }
            });
        }
    }

    private Handler mHandler = new Handler();
}
